package com.objcat.servicesecurity.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * Created by wxb on 2018/10/26 0026.
 * 本类是鉴权的决策类
 *
 * 4.流程来到鉴权的决策类AccessDecisionManager的实现类（MyAccessDecisionManager）中，
 * 它的decide方法可以决定当前用户是否能够访问资源。decide方法的参数中可以获得当前用户的验证信息、
 * 第3步中获得的资源所需角色信息，对这些角色信息进行匹配即可决定鉴权是否通过。当然，你也可以加入自
 * 己独特的判断方法，例如只要用户具有ROLE_ADMIN角色就一律放行；
 */
@Slf4j
@Component
public class MyAccessDecisionManager implements AccessDecisionManager {

    //忽略鉴权列表，此列表可放入配置或数据库
    @Value("${my.url.ignore}")
    private String[] ignoreUrls;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
            throws AccessDeniedException, InsufficientAuthenticationException {
        log.info("----进入MyAccessDecisionManager-----------------");
        /**
         * 对于下列特定网页的访问无需权限
         */
        String requestUrl = ((FilterInvocation) object).getRequestUrl();

        //若在忽略鉴权列表，则忽略
        if(checkUrlInIgnoreList(requestUrl)) {
            return;
        }

        //从authentication中获取当前用户具有的角色
        Collection<? extends GrantedAuthority> userAuthorities = authentication.getAuthorities();
        log.info("当前用户具有的角色数：{}",userAuthorities.size());
        log.info(userAuthorities.toString());
        //从configAttributes中获取访问资源所需要的角色，它来自MySecurityMetadataSource的getAttributes
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute attribute = iterator.next();
            String role = attribute.getAttribute();
            log.info("角色：{}",role);
            if ("ROLE_NONE".equals(role)) {
                log.info("none");
                if (authentication instanceof AnonymousAuthenticationToken) {
                    log.info("none1：未登录");
                    throw new BadCredentialsException("用户未登录");
                } else {
                    /**
                     * 当访问的资源不被任何角色可用时进入此处
                     * 若直接return
                     * 则代表无所属的资源可以被所有人访问
                     */
                    log.info("none2：登录但请求资源无角色所属");
                    throw new AccessDeniedException("你没有访问" + object + "的权限!");
//                    return;
                }
            }
            //逐一进行角色匹配
            for (GrantedAuthority authority : userAuthorities) {
                log.info("当前用户具有的角色:{}",authority.getAuthority());
                if (authority.getAuthority().equals("ROLE_ADMIN")) {
                    return; //用户具有ROLE_ADMIN权限，则可以访问所有资源
                }
                if (authority.getAuthority().equals(role)) {
                    return;  //匹配成功就直接返回
                }
            }
        }
        log.info("匹配失败");
        //不能完成匹配
        throw new AccessDeniedException("你没有访问" + object + "的权限!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    /**
     * 检测url是否在忽略鉴权列表中
     * 列表通过@Value注解，在配置文件中获取
     *
     * @param url
     * @return
     */
    public boolean checkUrlInIgnoreList(String url) {
        for (String ignoreUrl : ignoreUrls) {
            if(antPathMatcher.match(ignoreUrl, url)){
                return true;
            }
        }
        return false;
    }
}
